package packageDataAccess;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.sql.DataSource;
import javax.naming.InitialContext;
import javax.naming.Context;
import packageException.MotsClefsException;
import java.util.ArrayList;
import javax.naming.NamingException;
import packageException.DataException;

/**
 *
 * @author Lionel & Julien
 */
public class MotsClefsSyllathequeData {
    /**
     * Recherche les mots-clefs correspondant
     * 
     * @param syllabusId
     * @return ArrayList<String>
     * @throws MotsClefsException
     * @throws DataException  
     */
    public ArrayList<String> getMotsClefsById(int syllabusId) throws 
            MotsClefsException,
            DataException {
        ArrayList<String> tabMotsClefs = new ArrayList<String>();
        try {
            // Connexion à la base de données
            Context ctx = new InitialContext(); 
            DataSource source = (DataSource) ctx.lookup("jdbc/Syllatheque"); 
            Connection connexion = source.getConnection();
            
            // SQL
            String requeteSql = "SELECT * "
                    + "FROM MotsClefs "
                    + "WHERE syllabusMCId = ?"
                    + "ORDER BY motsClefs";

            // Traitement
            PreparedStatement prepStat = connexion.prepareStatement(requeteSql);
            prepStat.setInt(1, syllabusId);
            
            ResultSet donnees = prepStat.executeQuery();
            while(donnees.next()) {
                tabMotsClefs.add(donnees.getString("MotsClefs"));
            }
            
            // Fermeture de la connexion
            connexion.close();
        }
        catch(SQLException e) {
            // ERREUR
            throw new MotsClefsException(e.getMessage());
        }
        catch(NamingException e) {
            // ERREUR
            throw new DataException(e.getMessage());
        }
        return tabMotsClefs;
    }
}
